package com.ssy.lingxi.common.utils;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * MD5 32位摘要算法
 * @author 万宁
 * @date 2020-06-05
 * @version 2.0.0
 */
public class MD5Util {
	private static MD5Util instance = new MD5Util();

	private MD5Util() {
	}

	public static MD5Util Instance() {
		return instance;
	}

	/**
	 * MD5 32位算法
	 * @param utf8String utf-8编码字符串
	 * @return byte[]类型
	 */
	public byte[] MD32bitToBytes(String utf8String) throws NoSuchAlgorithmException {
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		return md5.digest(utf8String.getBytes(StandardCharsets.UTF_8));
	}
	
	/**
	 * MD5 32位算法，返回小写的16进制字符串
	 * @param utf8String utf-8编码字符串
	 * @return 小写的16进制字符串
	 */
	public String MD32bitToHexString(String utf8String) throws NoSuchAlgorithmException {
		byte[] bts = MD32bitToBytes(utf8String);
		if(bts == null){
			return "";
		}
		
		StringBuilder des = new StringBuilder();
        String tmp;
		for (byte bt : bts) {
			tmp = (Integer.toHexString(bt & 0xFF));
			if (tmp.length() == 1) {
				des.append("0");
			}
			des.append(tmp);
		}
        return des.toString();
	}
	
	/**
	 * MD5 32位算法，返回Base64字符串
	 * @param utf8String utf-8编码字符串
	 * @return Base64字符串
	 */
	public String MD32bitToBase64String(String utf8String) throws NoSuchAlgorithmException {
		byte[] bts = MD32bitToBytes(utf8String);
		if(bts == null){
			return "";
		}		
		return Base64.getEncoder().encodeToString(bts);        
	}

}
